package com.itheima.threadsynchronizedthird;


import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@AllArgsConstructor
public class Account {
    private String cardId;
    private int money = 0;
    private final Lock lk = new ReentrantLock(); // final保护锁对象

    public void draw(int drawMoney){
        // 加锁
        lk.lock();
        try {
            if(money >= drawMoney){
                System.out.println(Thread.currentThread().getName() + "取款中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 模拟取款
                money -= drawMoney;
                System.out.println(Thread.currentThread().getName() + "取款成功，余额为：" + money);
            }else{
                System.out.println(Thread.currentThread().getName() + "取款失败，余额不足");
            }
        } finally {
            // 解锁
            lk.unlock();
        }
    }
}
